#!/usr/bin/env python
#! -*- coding: utf-8 -*-

import sqlalchemy
import cx_Oracle
from sqlalchemy.orm import sessionmaker

from modules.oraclesrv import OracleSrv
from models.postgre.app_medicine import AppMedicine_Test
from config import db_bencao_app, ORCL_HIS

def formatConnectionString(dbconf):
    engine = dbconf['connector'] if 'connector' in dbconf else 'mysql'
    user = dbconf['user'] if 'user' in dbconf else 'guest'
    pwd = dbconf['pwd'] if 'pwd' in dbconf else ''
    host = dbconf['host'] if 'host' in dbconf else 'localhost'
    port = dbconf['port'] if 'port' in dbconf else 3306
    dbname = dbconf['db'] if 'db' in dbconf else 'guest'
    driverpart = '+'+ dbconf['driver'] if 'driver' in dbconf else ''

    return '%s%s://%s:%s@%s:%d/%s' % (engine, driverpart, user, pwd, host, port, dbname)

def db_connect():
    engine_bencao_app = sqlalchemy.create_engine(formatConnectionString(db_bencao_app), 
                encoding=db_bencao_app['encoding'] if 'encoding' in db_bencao_app else 'utf-8',
                pool_pre_ping=True)
    DbSessionBencao = sessionmaker(bind=engine_bencao_app, autoflush=True, autocommit=False, expire_on_commit=True)
    postgre_db = DbSessionBencao()

    his_obj = OracleSrv(ORCL_HIS['host'], ORCL_HIS['port'], ORCL_HIS['username'], \
        ORCL_HIS['password'], ORCL_HIS['dsn'])

    return postgre_db, his_obj

def compare(medicine, his_obj):
    QUERY_SQL = "select (case JBYWBZ when 1 then 1 else 0 end) as basic_drug,(case when ksdj is null then ksdj else 0 end) as antibacterial,\
            (case when (yc_ypjx like '%%注射%%') or (yc_ypjx like '%%针剂%%') then 1 else 0 end) as injection, type as cn_west_flag from yk_ypml where ypxh = '%s'"
    exec_sql = QUERY_SQL % str(medicine.med_code)
    his_result_list = his_obj.exec_query(exec_sql)
    his_result = []
    if his_result_list:
        his_result = list(his_result_list[0])

    if his_result:
        # 基本药物
        if medicine.basic_drug != int(his_result[0]):
            medicine.basic_drug = int(his_result[0])
        # 抗菌药物等级
        if medicine.antibacterial != int(his_result[1]):
            medicine.antibacterial = int(his_result[1])
        # 针剂
        if medicine.injection != int(his_result[2]):
            medicine.injection = int(his_result[2])
        # 中西药判断
        if medicine.cn_west_flag != int(his_result[3]):
            medicine.cn_west_flag = int(his_result[3])
    
    return medicine

def main():
    postgre_db, his_obj = db_connect()
    appmedicine_list = postgre_db.query(AppMedicine_Test).filter_by(app_id='11-0001')
    i = 0
    for appmedicine in appmedicine_list:
        i += 1
        print(i,appmedicine.med_name,appmedicine.med_code)
        appmedicine = compare(appmedicine, his_obj)
        postgre_db.commit()
